/*
 * @Author: lyuan2018
 * @Date: 2019-08-21 10:09:24
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-05-22 14:50:22
 */
import { observable, action, toJS } from 'mobx';
import { message } from 'antd';
import { WeaForm } from 'comsMobx';
import { WeaLocaleProvider } from 'ecCom';
import * as Api from '../../apis/contacts';
import { ValidateForm } from '../emailSetting/util';

const getLabel = WeaLocaleProvider.getLabel;
const CONDITION = () => {
  let condition = {
    conditions: [
      {
        defaultshow: true,
        items: [{
          colSpan: 2,
          conditionType: 'INPUT', // 类型
          rules: 'required|string', // 校验规则
          domkey: [
            'groupName',
          ],
          fieldcol: 14,
          label: getLabel(30127, '分组名称'),
          labelcol: 8,
          value: '',
          viewAttr: 3,
        }],
      },
    ],
  };
  return condition;
};
const initalState = {
  sysgroups: [],
  usergroups: [],
  topLoading: true,
  contentLoading: true,
  usercontent: [],
  curgroup: '',
  curgroupId: '',
  curPage: 1,
  hasMore: true,
  addContactTitle: '',
  addContactFileds: [],
  addContactLoading: false,
  addContactGroups: [],
  contactSelect: [],
  editId: '',
  newGroupFields: [],
  addmailContact: {},
};
export default class EmailContactStore {
  @observable addContactForm = new WeaForm(); // 添加联系人Form
  @observable newGroupForm = new WeaForm(); // 新建分组Form
  @observable sysgroups = initalState.sysgroups; // 系统分组
  @observable usergroups = initalState.usergroups; // 个人分组
  @observable topLoading = initalState.topLoading; // 头部loading
  @observable contentLoading = initalState.contentLoading; // 内容loading
  @observable usercontent = initalState.usercontent; // 联系人
  @observable curgroup = initalState.curgroup; // 当前联系人分组
  @observable curgroupId = initalState.curgroupId; // 当前联系人分组ID
  @observable curPage = initalState.curPage; // 当前页面
  @observable hasMore = initalState.hasMore; // 标志当前联系人页面是否还有数据
  @observable addContactTitle = initalState.addContactTitle; // 添加联系人dialogTitle
  @observable addContactFileds = initalState.addContactFileds; // 添加联系人Condition
  @observable addContactLoading = initalState.addContactLoading; // 添加联系人Loading
  @observable addContactGroups = initalState.addContactGroups; // 添加联系人分组
  @observable contactSelect = initalState.contactSelect; // 当前选择联系人
  @observable editId = initalState.editId; // 编辑联系人记录ID
  @observable newGroupFields = initalState.newGroupFields; // 新建分组Condition
  @observable addmailContact = initalState.addmailContact; // 编辑联系人赋值Contact

  @action setStoreState = (params) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
  }

  @action clear = () => this.setStoreState(initalState);

  // 头部分组请求
  @action getContactCountList = (params = {}) => {
    this.topLoading = true;
    Api.contactCountList().then((res) => {
      this.sysgroups = res.sysGroups || [];
      this.usergroups = res.userGroups || [];
      if (Object.keys(params).length > 0) {
        let tempGroup;
        if (params.groupId * 1 === 0 || params.groupId * 1 === -1) {
          tempGroup = res.sysGroups.filter(v => v.goutId * 1 === params.groupId * 1)[0];
        } else {
          tempGroup = res.userGroups.filter(v => v.goutId * 1 === params.groupId * 1)[0];
        }
        this.curgroup = `${tempGroup.groupName} (${tempGroup.count})`;
        this.curgroupId = params.groupId;
      } else {
        this.curgroup = `${res.sysGroups[0].groupName} (${res.sysGroups[0].count})`;
        this.curgroupId = res.sysGroups[0].goutId;
      }
      this.topLoading = false;
    });
  }

  // 主页列表请求
  @action getContactList = (params, needloading = true, loadMore = false, callback) => {
    needloading && (this.contentLoading = true);
    params = { pageSize: 35, mailgroupid: this.curgroupId, current: 1, ...params };
    if (loadMore) {
      params = { ...params, current: this.curPage };
    } else {
      this.hasMore = true;
      this.curPage = 1;
    }
    if (this.hasMore) {
      Api.contactList(params).then((res) => {
        let selectIds = this.contactSelect.map(v => v.id);
        let newDatas = res.datas.map((v) => {
          if (selectIds.indexOf(v.id) > -1) {
            return { ...v, contactChecked: 1 };
          }
            return { ...v, contactChecked: 0 };
        });
        this.usercontent = loadMore ? [...this.usercontent, ...newDatas] : newDatas || [];
        if (res.current * res.pageSize >= res.total) this.hasMore = false;
        if (callback && typeof callback === 'function') callback();
        needloading && (this.contentLoading = false);
      });
    }
  }

  updateContactList = (ids, params) => {
    if (!ids) return;
    let curData = [];
    curData = toJS(this.usercontent).map((v) => {
      if (ids.split(',').indexOf(v.id) > -1) {
        return {
          ...v,
          ...params,
        };
      }
      return v;
    });
    this.usercontent = curData;
  }

  // 头部select选项change事件
  @action selectChange = (value, callback) => {
    let chooseGroup = value.split('-');
    if (value === 'new') { // 新建分组
      callback();
    } else {
      if (chooseGroup[0] === '') { // 未分组
        this.curgroup = `${chooseGroup[2]} (${chooseGroup[3]})`;
        this.curgroupId = -1;
      } else {
        this.curgroup = `${chooseGroup[1]} (${chooseGroup[2]})`;
        this.curgroupId = chooseGroup[0];
      }
      this.getContactList();
      this.contactSelect = [];
    }
  }

  // 滚动到底部时触发的方法
  @action onScrollEnd = () => {
    if (this.hasMore) {
      this.curPage++;
      this.getContactList('', true, true);
    }
  }

  // 分组保存
  @action groupSubmit = (params) => {
    Api.contactOperation(params).then((res) => {
      if (res.status === '1') {
        this.getContactList('', true, false, () => {
          if (this.curgroupId == -1) { // 未分组
            this.contactSelect = toJS(this.usercontent).filter(item => item.contactChecked === 1);
          }
        });
        this.getContactCountList({ groupId: this.curgroupId });
      }
    });
  }

  // 新建分组
  @action newGroup = (params, callback) => {
    Api.contactOperation(params).then((res) => {
      if (res.api_status) {
        this.getContactCountList({ groupId: this.curgroupId });
        if (callback) callback();
      } else {
        message.error(res.api_msg || getLabel(384400, '添加失败，请重试！'));
      }
    });
  }

  // 添加联系人
  @action contactCondition = (params, isInit = true, callback) => {
    isInit && (this.addContactLoading = true);
    Api.contactCondition(params).then((res) => {
      this.addContactForm.initFormFields(res.conditions);
      this.addContactFileds = res.conditions || [];
      this.addContactGroups = res.groups || [];
      this.addmailContact = res.mailContact || {};
      if (callback) callback(this.addContactForm);
      this.addContactLoading = false;
    });
  }

  // 添加联系人--保存联系人
  @action onSaveContact = (params, callback) => {
    ValidateForm(this.addContactForm, () => {
      let formParams = this.addContactForm.getFormParams();
      params = { ...formParams, ...params };
      this.editId !== '' && (params = { ...params, id: this.editId });
      Api.contactOperation(params).then((res) => {
        if (res.api_status) {
          message.success(getLabel(83551, '保存成功！'));
        } else {
          message.error(res.api_msg || getLabel(384400, '添加失败，请重试！'));
        }
        if (callback) callback(res, params.id);
      });
    });
  }

  // 选择
  @action changeContactSelect = (v, data) => {
    this.usercontent = this.usercontent.map((item) => {
      if (item.id === data.id) {
        return { ...item, contactChecked: v * 1 };
      }
        return item;
    });
    this.contactSelect = toJS(this.usercontent).filter(item => item.contactChecked === 1);
  }

  // 是否全选
  @action changeAllContactSelect = (v) => {
    this.usercontent = this.usercontent.map(item => ({ ...item, contactChecked: v * 1 }));
    this.contactSelect = v * 1 ? this.usercontent : [];
  }

  // 分组移动 || 复制 || 从该组移除
  @action moveCopyGroup = (params, callback) => {
    Api.contactOperation(params).then((res) => {
      if (res.status && !res.api_msg) {
        this.getContactList();
        this.getContactCountList({ groupId: this.curgroupId });
        this.contactSelect = [];
        callback && callback();
      } else {
        message.error(res.api_msg || getLabel(384402, '操作失败，请重试！'));
      }
    });
  }

  // 新建分组并移动
  @action getCondition = (callback) => {
    let newGroupCondition = CONDITION();
    this.newGroupForm.initFormFields(newGroupCondition.conditions);
    this.newGroupFields = newGroupCondition.conditions;
    if (callback) callback();
  }

  // 新建 || 编辑 分组
  @action updateGroup = (params) => {
    Api.contactOperation(params).then((res) => {
      if (res.api_status) {
        this.getContactCountList({ groupId: params.groupId });
      } else {
        message.error(res.api_msg || getLabel(384402, '操作失败，请重试！'));
      }
    });
  }

  // 删除分组
  @action deleteGroup = (params) => {
    Api.contactOperation(params).then((res) => {
      if (res.status) {
        this.curgroup = '';
        this.curgroupId = '';
        this.getContactCountList();
        this.getContactList();
        this.contactSelect = [];
        message.success(getLabel(83472, '删除成功！'));
      } else {
        message.error(getLabel(384401, '删除失败，请重试！'));
      }
    });
  }
}
